import { defineStore } from 'pinia'
import { login, logout } from '@/api/system/auth'
import { getInfo } from '@/api/system/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { IUserInfo, ILoginParams } from '@/types/user'

interface IUserState {
  userInfo: IUserInfo | null;
  roles: string[];
  name: string;
  avatar: string;
}

interface IUserActions {
  login(userInfo: ILoginParams): Promise<void>;
  getInfo(): Promise<{ roles: string[]; id: number }>;
  logout(): Promise<void>;
  resetToken(): void;
}

interface IUserGetters {
  username: string | undefined;
  nickname: string | undefined;
  token: string | null;
}

export type UserStore = {
  state: IUserState;
  actions: IUserActions;
  getters: IUserGetters;
}

export const useUserStore = defineStore('user', {
  state: (): IUserState => ({
    userInfo: null,
    roles: [],
    name: '',
    avatar: ''
  }),
  
  getters: {
    username: (state) => state.userInfo?.username,
    nickname: (state) => state.userInfo?.nickname,
    token: () => getToken()
  },
  
  actions: {
    // 登录
    async login(userInfo: ILoginParams) {
      try {
        const { username, password } = userInfo
        const { data } = await login({ username: username.trim(), password })
        setToken(data.token)
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getInfo() {
      try {
        const { data } = await getInfo()
        console.log('User info response:', data)
        
        if (!data || !data.userInfo) {
          throw new Error('获取用户信息失败')
        }

        // 处理角色信息
        let roles: string[] = []
        if (data.userInfo.roles) {
          if (Array.isArray(data.userInfo.roles)) {
            roles = data.userInfo.roles
          } else if (typeof data.userInfo.roles === 'string') {
            roles = [data.userInfo.roles]
          } else if (typeof data.userInfo.roles === 'object') {
            roles = Object.values(data.userInfo.roles)
          }
        }
        
        // 如果没有角色信息，设置一个默认角色
        if (roles.length === 0) {
          roles = ['user']
        }
        
        this.roles = roles
        this.name = data.userInfo.name || data.userInfo.username || ''
        this.avatar = data.userInfo.avatar || ''
        this.userInfo = data.userInfo
        return Promise.resolve({ roles, id: data.userInfo.id })
      } catch (error) {
        console.error('Get user info error:', error)
        this.roles = []
        this.name = ''
        this.avatar = ''
        this.userInfo = null
        return Promise.reject(error)
      }
    },
    
    // 登出
    async logout() {
      try {
        await logout()
        this.roles = []
        this.userInfo = null
        this.name = ''
        this.avatar = ''
        removeToken()
        resetRouter()
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 重置 Token
    resetToken() {
      this.roles = []
      this.name = ''
      this.avatar = ''
      this.userInfo = null
      removeToken()
    }
  },
  
  persist: true
})